/**
 * 瓦片图层类
 * 支持多种瓦片数据源的加载和显示
 */

import { Map as OlMap } from 'ol';
import { Tile as TileLayer } from 'ol/layer';
import { XYZ, OSM, TileImage } from 'ol/source';
import { BaseLayer } from './BaseLayer';
import { TileLayerOptions } from '../types';

/**
 * 瓦片图层类
 */
export class TileLayerWrapper extends BaseLayer {
  /** 图层配置 */
  protected options: TileLayerOptions;
  /** 瓦片数据源 */
  private source: TileImage | null = null;

  /**
   * 构造函数
   * @param options 图层配置
   */
  constructor(options: TileLayerOptions = {}) {
    super(options);
    this.options = {
      tileSize: 256,
      maxZoom: 18,
      minZoom: 0,
      projection: 'EPSG:3857',
      crossOrigin: 'anonymous',
      ...options
    };
  }

  /**
   * 创建图层
   */
  protected createLayer(): void {
    const { url, urls, tileSize, maxZoom, minZoom, projection, crossOrigin, tileLoadErrorRetryCount } = this.options;

    // 如果没有URL，使用OSM作为默认
    if (!url && !urls) {
      this.source = new OSM();
    } else {
      // 使用XYZ瓦片源
      const urlArray = urls || (url ? [url] : []);
      
      const xyzOptions: any = {
        url: urlArray[0],
        urls: urlArray.length > 1 ? urlArray : undefined,
        tileSize: tileSize || 256,
        maxZoom: maxZoom,
        minZoom: minZoom,
        projection: projection,
        crossOrigin: crossOrigin
      };
      
      // tileLoadErrorRetryCount 可能在某些版本中不存在，使用条件添加
      if (tileLoadErrorRetryCount !== undefined) {
        xyzOptions.tileLoadErrorRetryCount = tileLoadErrorRetryCount;
      }
      
      this.source = new XYZ(xyzOptions);
    }

    this.layer = new TileLayer({
      source: this.source
    });
  }

  /**
   * 更新瓦片URL
   * @param url 新的瓦片URL
   */
  updateUrl(url: string): void {
    this.options.url = url;
    if (this.map && this.layer && this.source instanceof XYZ) {
      this.source.setUrl(url);
    }
  }

  /**
   * 更新瓦片URL数组
   * @param urls 新的瓦片URL数组
   */
  updateUrls(urls: string[]): void {
    this.options.urls = urls;
    if (this.map && this.layer && this.source instanceof XYZ) {
      this.source.setUrls(urls);
    }
  }

  /**
   * 获取瓦片数据源
   * @returns 瓦片数据源
   */
  getSource(): TileImage | null {
    return this.source;
  }
}

